package utils

import (
	"fmt"
	"github.com/go-redis/redis"
	jsoniter "github.com/json-iterator/go"
	"log"
)

func ScanMapToDb(this, parent map[string]interface{}, pipe redis.Pipeliner,typeName string) {
	var (
		dbText,
		key   string
		value interface{}
		ok    bool
		perMap map[string]interface{}

	)
	perMap = make(map[string]interface{})
	for key, value = range this {
		if key != "east" && key != "west" && key != "north" && key != "south" {
			perMap[key] = value
		}
	}
	for _, key = range []string{"east", "west", "north", "south"} {
		if value, ok = this[key]; ok {
			if value != nil {
				perMap[key] = map[string]interface{}{
					"id" : value.(map[string]interface{})["id"],
					"name" : value.(map[string]interface{})["name"],
				}
				ScanMapToDb(value.(map[string]interface{}), this, pipe,typeName)
			} else {
				perMap[key] = map[string]interface{}{
					"id" : nil,
					"name" : nil,
				}
			}
		} else {
			perMap[key] = map[string]interface{}{
				"id" : parent["id"],
				"name" : parent["name"],
			}
		}
	}
	dbText,_ = jsoniter.MarshalToString(perMap)
	pipe.HSet(typeName,fmt.Sprintf("%.0f",perMap["id"].(float64)),dbText)
}
func normalScanDataToDb(this []interface{}, pipe redis.Pipeliner, typeName string,redisDB *redis.Client,dataType string) {
	var (
		data interface{}
		mapId,
		mapType,
		normalDataText,
		mapText string
		mapData map[string]interface{}
		value []interface{}
		ok               bool
	)
	for _,data = range this{
		mapId = fmt.Sprintf("%.0f",data.(map[string]interface{})["map"].(map[string]interface{})["id"].(float64))
		mapType = data.(map[string]interface{})["map"].(map[string]interface{})["name"].(string)
		if mapText = redisDB.HGet(mapType,mapId).Val();mapText == ""{
			log.Fatal("mapId不存在")
		}
		mapData,_ = UnMarshal(mapText)
		mapData = mapData["unmarshalData"].(map[string]interface{})
		if value,ok = mapData[dataType].([]interface{});ok{
			value = append(value, map[string]interface{}{
				"id" : data.(map[string]interface{})["id"],
				"name": data.(map[string]interface{})["name"],
				//"type" : typeName,
			})
		}else{
			value = append([]interface{}{},map[string]interface{}{
				"id" : data.(map[string]interface{})["id"],
				"name": data.(map[string]interface{})["name"],
				//"type" : typeName,
			})
		}
		if data.(map[string]interface{})["isAlive"].(bool){
			mapData[dataType] = value
			mapText,_ = jsoniter.MarshalToString(mapData)
			redisDB.HSet(mapType,mapId,mapText)
			normalDataText,_ = jsoniter.MarshalToString(data)
			pipe.HSet(dataType,fmt.Sprintf("%.0f",data.(map[string]interface{})["id"].(float64)),normalDataText)
		}
	}
}
func ScanNpcToDb(this []interface{}, pipe redis.Pipeliner,typeName string,redisDB *redis.Client) {
	normalScanDataToDb(this, pipe, typeName,redisDB,"npcList")
}
func ScanMonsterToDb(this []interface{}, pipe redis.Pipeliner,typeName string,redisDB *redis.Client) {
	normalScanDataToDb(this, pipe, typeName,redisDB,"monsterList")
}

